const { Op } = require('sequelize')
const Question = require('../model/question.model')

// 编辑问题
const editQuestion = async ({ questionId, content }) => {
  const whereOption = { id: questionId }
  const newQuestion = {}
  content && Object.assign(newQuestion, { content })

  return await Question.update(newQuestion, {
    where: whereOption
  })
}

// 创建问题
const createQuestion = async ({ content, userId }) => {
  const result = await Question.create({
    questioner: userId,
    content,
  })

  return result
}

const addTagSv = async ({ questionId, tags }) => {
  const whereOption = { id: questionId }
  const newQuestion = {}
  tags && Object.assign(newQuestion, { tags })

  return await Question.update(newQuestion, { where: whereOption })
}

// 提高问题权重
const upgradeQuestionWeight = async (questionId) => {
  const whereOption = {}
  if (!questionId) return console.warn('[upgradeQuestionWeight warn]: questionId 不存在 ->', questionId)
  Object.assign(whereOption, { id: questionId })

  const result = await Question.increment('weight', { where: whereOption })
  return result
}

// 获取本用户问题列表
const getQuestionList = async ({ userId, page, limit, sortBy, keyword }) => {
  const whereOption = {}
  userId && Object.assign(whereOption, { questioner: userId })
  keyword && Object.assign(whereOption, { content: { [Op.substring]: keyword } })

  const amount = await Question.count({ where: whereOption })
  const result = await Question.findAll({
    offset: limit * (page - 1),
    limit,
    where: whereOption,
    order: [[sortBy || 'weight', sortBy === 'content' ? 'ASC' : 'DESC']]
  })

  return [result, amount]
}

// 通过id获取某个问题
const getQuestionByQuestionId = async (questionId) => {
  const whereOption = {}
  questionId && Object.assign(whereOption, { id: questionId })

  const result = await Question.findOne({ where: whereOption })

  return result
}

// 通过问题内容获取某个问题
const getQuestionByContent = async (content) => {
  const whereOption = {}
  content && Object.assign(whereOption, { content })

  const result = await Question.findOne({ where: whereOption })

  return result
}

const destroyQuestionByQuestionId = async (questionId) => {
  const whereOption = {}
  questionId && Object.assign(whereOption, { id: questionId })

  const result = await Question.destroy({ where: whereOption })

  return result
}

module.exports = {
  editQuestion,
  createQuestion,
  addTagSv,
  upgradeQuestionWeight,
  getQuestionByQuestionId,
  getQuestionByContent,
  getQuestionList,
  destroyQuestionByQuestionId,
}